<script setup lang="ts">
defineOptions({
  name: "ALL_FAB_MONITORING_SPECOVERVIEW_SETSPEC"
});

import { ref, computed, onMounted, provide, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { queryFabSPECDetail, createFabSPEC, editFabSPEC } from "@/api/modules/fab";
import { useRouterStoreHook } from "@/store/modules/router";
import { ArrowLeft } from "@px-ui/icons-vue";
import ReCollapse from "@/components/ReCollapse";
import ReTeleport from "@/components/ReTeleport";
import baseInfo from "./components/baseInfo.vue";
import limit from "./components/limit.vue";
import eventConfig from "./components/eventConfig.vue";
import previewSpec from "./components/previewSpec.vue";
import { cloneDeep } from "@pureadmin/utils";
import { initDefaultColor } from "./hooks";

const route = useRoute();
const router = useRouter();
const routerStore = useRouterStoreHook();

const baseInfoRef = ref<InstanceType<typeof baseInfo> | null>(null);
const limitRef = ref<InstanceType<typeof limit> | null>(null);
const eventConfigRef = ref<InstanceType<typeof eventConfig> | null>(null);
const previewSpecVisible = ref<boolean>(false);
const previewSpecData = ref<Record<string, any>>(null);
const extraParams = ref<Record<string, any>>({});

const baseInfoData = ref<Record<string, any>>({
  eqpId: "",
  controlLine: ["up", "down"],
  quotaSingleCode: "",
  indicatorLevel: "",
  classCode: "",
  systemCode: "",
  point: "",
  pointUnit: "",
  startValue: undefined,
  step: undefined
});

const limitData = ref<Record<string, any>>({
  uslValue: undefined,
  uslColor: initDefaultColor("uslColor"),
  uclValue: undefined,
  uclColor: initDefaultColor("uclColor"),
  uwlValue: undefined,
  uwlColor: initDefaultColor("uwlColor"),
  u3lValue: undefined,
  targetValue: undefined,
  targetColor: initDefaultColor("targetColor"),
  lwlValue: undefined,
  lwlColor: initDefaultColor("lwlColor"),
  lclValue: undefined,
  lclColor: initDefaultColor("lclColor"),
  lslValue: undefined,
  lslColor: initDefaultColor("lslColor"),
  l3lValue: undefined
});

const eventConfigData = ref<Record<string, any>>({
  notifyType: "CONSUME",
  notifyMethods: [],
  notifyUsers: [],
  notifyNoteCustom: ""
});

provide("baseInfoData", baseInfoData);
provide("limitData", limitData);

const submitDisabled = computed(() => !baseInfoData.value.eqpId || !baseInfoData.value.quotaSingleCode);
const previewDisabled = computed(() => {
  if (baseInfoData.value.controlLine?.length === 2) {
    return !(
      limitData.value.uslValue ||
      limitData.value.uclValue ||
      limitData.value.uwlValue ||
      limitData.value.targetValue ||
      limitData.value.lwlValue ||
      limitData.value.lclValue ||
      limitData.value.lslValue
    );
  } else if (baseInfoData.value.controlLine?.length === 1) {
    if (baseInfoData.value.controlLine?.includes("up")) {
      return !(limitData.value.uslValue || limitData.value.uclValue || limitData.value.uwlValue || limitData.value.targetValue);
    } else if (baseInfoData.value.controlLine?.includes("down")) {
      return !(limitData.value.targetValue || limitData.value.lwlValue || limitData.value.lclValue || limitData.value.lslValue);
    } else {
      return true;
    }
  } else {
    return true;
  }
});

const initLimitAndEventConfigData = (data: any) => {
  limitRef.value.init(data);
  eventConfigRef.value.init(data);
};

const baseInfoChangeHandler = async (type: string, form?: Record<string, any>, data?: Record<string, any>) => {
  if (type === "clear") {
    baseInfoRef.value.clearForm();
    limitRef.value.clearForm();
    eventConfigRef.value.clearForm();
  } else if (type === "quotaSingleCode") {
    extraParams.value = {};
    const { relationSingleCode = null, spcIndicatorDTO = null, id = null } = data;
    extraParams.value["relationSingleCode"] = relationSingleCode;
    if (id || spcIndicatorDTO?.id) {
      extraParams.value["id"] = id || spcIndicatorDTO.id;
    }
    initLimitAndEventConfigData(data);
  }
};

const cancelHandler = () => {
  router.go(-1);
};

const previewHandler = () => {
  const limitDataForm = formatSpecColor(limitData.value as Record<string, any>);
  previewSpecData.value = { ...baseInfoData.value, ...limitDataForm };
  previewSpecVisible.value = true;
};

const formatSpecColor = (form: Record<string, any>) => {
  if (!form) return {};
  const {
    uslValue = "",
    uclValue = "",
    uwlValue = "",
    u3lValue = "",
    targetValue = "",
    lwlValue = "",
    lclValue = "",
    lslValue = "",
    l3lValue = "",
    uslColor = "",
    uclColor = "",
    uwlColor = "",
    targetColor = "",
    lwlColor = "",
    lclColor = "",
    lslColor = ""
  } = form;

  const specColor = [
    {
      code: "uslColor",
      colorValue: uslColor
    },
    {
      code: "uclColor",
      colorValue: uclColor
    },
    {
      code: "uwlColor",
      colorValue: uwlColor
    },
    {
      code: "targetColor",
      colorValue: targetColor
    },
    {
      code: "lwlColor",
      colorValue: lwlColor
    },
    {
      code: "lclColor",
      colorValue: lclColor
    },
    {
      code: "lslColor",
      colorValue: lslColor
    }
  ];
  return {
    uslValue,
    uclValue,
    uwlValue,
    u3lValue,
    targetValue,
    lwlValue,
    lclValue,
    lslValue,
    l3lValue,
    specColor
  };
};

const submitHandler = async () => {
  let baseInfoForm = await baseInfoRef.value.validate();
  let limitForm = await limitRef.value.validate();
  let eventConfigForm = await eventConfigRef.value.validate();
  baseInfoForm = cloneDeep(baseInfoForm as Record<string, any>);
  limitForm = formatSpecColor(limitForm as Record<string, any>);
  eventConfigForm = cloneDeep(eventConfigForm as Record<string, any>);
  delete eventConfigForm.notifyUsersIds;
  const config = { ...eventConfigForm };
  const params = { ...extraParams.value, ...baseInfoForm, ...limitForm, config };
  if ("id" in params) {
    await editFabSPEC(params);
  } else {
    await createFabSPEC(params);
  }
  const className = routerStore.getSubject.toLowerCase();
  const path = `/${className}/fab/monitoring/specOverView`;
  router.push({ path });
};

const baseInfoVisibleChangeHandler = async (flag: boolean) => {
  await nextTick();
  if (flag) {
    const {
      query: { id = "", quotaSingleCode = "", eqpId = "" }
    } = route;
    if (id) {
      const params = { id };
      const res = await queryFabSPECDetail(params);
      if (!res) return;
      baseInfoRef.value?.init(res, true);
    } else if (eqpId && quotaSingleCode) {
      baseInfoRef.value?.init({ eqpId, quotaSingleCode });
    }
  }
};

const limitVisibleChangeHandler = async (flag: boolean) => {
  await nextTick();
  if (flag) {
    const {
      query: { id = "", quotaSingleCode = "", eqpId = "" }
    } = route;
    if (id) {
      const params = { id };
      const res = await queryFabSPECDetail(params);
      if (!res) return;
      limitRef.value.init(res);
    }
  }
};

const eventConfigVisibleChangeHandler = async (flag: boolean) => {
  await nextTick();
  if (flag) {
    const {
      query: { id = "", quotaSingleCode = "", eqpId = "" }
    } = route;
    if (id) {
      const params = { id };
      const res = await queryFabSPECDetail(params);
      if (!res) return;
      eventConfigRef.value.init(res);
    }
  }
};

const init = async () => {
  const {
    query: { id = "", quotaSingleCode = "", eqpId = "" }
  } = route;
  if (id) {
    const params = { id };
    const res = await queryFabSPECDetail(params);
    if (!res) return;
    baseInfoRef.value?.init(res, true);
    initLimitAndEventConfigData(res);
  } else if (eqpId && quotaSingleCode) {
    baseInfoRef.value?.init({ eqpId, quotaSingleCode });
  }
};

onMounted(async () => {
  await init();
});
</script>

<template>
  <div class="set-spec-add">
    <div class="add-btn">
      <px-button type="primary" :icon="ArrowLeft" @click="cancelHandler">返回</px-button>
    </div>
    <div class="add-content">
      <div class="add-content-item">
        <ReCollapse title="基础信息" @visibleChange="baseInfoVisibleChangeHandler">
          <baseInfo ref="baseInfoRef" v-model="baseInfoData" @change="baseInfoChangeHandler" />
        </ReCollapse>
      </div>

      <div class="add-content-item">
        <ReCollapse title="上下限设置" @visibleChange="limitVisibleChangeHandler">
          <limit ref="limitRef" v-model="limitData" />
        </ReCollapse>
      </div>

      <div class="add-content-item">
        <ReCollapse title="事件配置" @visibleChange="eventConfigVisibleChangeHandler">
          <eventConfig ref="eventConfigRef" v-model="eventConfigData" />
        </ReCollapse>
      </div>

      <div class="add-content-item add-content-preview">
        <px-button type="primary" plain :disabled="previewDisabled" @click="previewHandler">预览</px-button>
      </div>
    </div>
    <ReTeleport submitText="保存" :submitDisabled="submitDisabled" @cancel="cancelHandler" @submit="submitHandler" />
    <previewSpec v-if="previewSpecVisible" v-model="previewSpecVisible" :data="previewSpecData" isEdit />
  </div>
</template>

<style lang="scss" scoped>
.set-spec-add {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
  background-color: #fff;

  .add-content {
    display: flex;
    flex: 1;
    flex-direction: column;
    gap: 16px;

    .add-content-item {
      width: 100%;
    }

    .add-content-preview {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 60px;
    }
    // 应测试（雪辉）要求去掉自动校验icon
    :deep(.px-form-item) {
      .px-input__validateIcon {
        display: none;
      }
    }
  }
}
</style>
